<?php

namespace App\Http\Controllers\admin;

use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use App\Models\Role;
use App\Models\Auth;
use App\Models\RoleAuth;
use yii\db\Exception;
use Illuminate\Support\Facades\DB;

class RoleController extends BaseController
{
    //
    public function index(Request $request){
        if($request->isMethod('post')){
            $page = $request->input('page',1);
            $limit = $request->input('limit',20);
            $page = ($page-1)*$limit;;
            $result = Role::getRoleInfos($page,$limit);
            return $this->showList($result,count(Role::where('status','=',1)->get()));
        }
        return view('admin.role.index');
    }

    public function add(Request $request){
        if($request->isMethod('post')){
            $arr = $request->except(['_token']);
            $arr['create_time'] = $arr['update_time'] = date('Y-m-d H:i:s',time());
            $arr['create_id'] = $arr['last_update_id'] = session('user.id');
            if(Role::insert($arr)){
                return $this->success('添加成功',asset('/role/index'));
            }else{
                return $this->error('添加失败');
            }
        }
        return view('admin.role.add');
    }

    public function edit(Request $request){
        if($request->isMethod('post')){
            $arr = $request->except(['_token','id']);
            if(!$request->filled('id')){
                return $this->error('数据丢失');
            }
            $arr['update_time'] = date('Y-m-d H:i:s',time());
            $arr['last_update_id'] = session('user.id');
            if(Role::where('id','=',$request->id)->update($arr)){
                return $this->success('编辑成功',asset('/role/index'));
            }else{
                return $this->error('编辑失败');
            }
        }
        if(!$request->filled('id')){
            return $this->error('数据丢失','/role/index');
        }
        $roleinfo = Role::find($request->id);
        return view('admin.role.edit',['roleinfo'=>$roleinfo]);
    }

    public function del(Request $request){
        if($request->filled('id')){
            if(Role::where('id','=',$request->id)->update(['status'=>'0'])){
                return $this->success('删除成功',asset('/role/index'));
            }
            return $this->error('删除失败');
        }
        return $this->error('数据丢失');
    }

    public function fp(Request $request){
        if(!$request->filled('id')){
            return $this->error('数据丢失');
        }
        if($request->isMethod('post')){
            if(!$request->filled('id_list')){
                return $this->error('至少选择一个权限');
            }
            /**开启事务*/
            try {
                DB::transaction(function () use($request) {
                    $idList = explode(',',$request->input('id_list'));//新的权限数组
                    $authId = RoleAuth::where('role_id',$request->id)->where('status','=','1')->pluck('Auth_id')->toArray();//旧的全部权限
                    $authIdAll = RoleAuth::where('role_id',$request->id)->where('status','=','0')->pluck('Auth_id')->toArray();//旧的已经删除权限
                    $authIdMeger = array_merge($authId, $authIdAll,);
//            去除部分已有权限
                    $dels = array_diff($authId, $idList);
                    if ($dels != []) {
                        $dels_arr['update_time'] = date('Y-m-d H:i:s', time());
                        $dels_arr['last_update_id'] = session('user.id');
                        $dels_arr['status'] = '0';
                        foreach ($dels as $v) {
                            //更新状态
                            RoleAuth::where('auth_id', '=', (int)$v)->where('role_id', '=', $request->id)->update($dels_arr);
                        }
                    }
//部分已删除权限，更新
                    $del_updates = array_intersect($idList, $authIdAll);
                    if ($del_updates != []) {
                        $del_updates_arr['update_time'] = date('Y-m-d H:i:s', time());
                        $del_updates_arr['last_update_id'] = session('user.id');
                        $del_updates_arr['status'] = '1';
                        foreach ($del_updates as $v) {
                            //更新状态
                            RoleAuth::where('auth_id', '=', (int)$v)->where('role_id', '=', $request->id)->update($del_updates_arr);
                        }
                    }
//            添加新权限
                    $adds = array_diff($idList, $authIdMeger);
                    if ($adds != []) {
                        $adds_arr['create_time'] = $adds_arr['update_time'] = date('Y-m-d H:i:s', time());
                        $adds_arr['create_id'] = $adds_arr['last_update_id'] = session('user.id');
                        $adds_arr['status'] = '1';
                        $adds_arr['role_id'] = $request->id;
                        foreach ($adds as $v) {
                            $adds_arr['auth_id'] = (int)$v;
                            RoleAuth::insert($adds_arr);
                        }
                    }
//            更新部分旧权限
                    $updates = array_intersect($idList, $authId);
                    if ($updates != []) {
                        $updates_arr['update_time'] = date('Y-m-d H:i:s', time());
                        $updates_arr['last_update_id'] = session('user.id');
                        //更新状态
                        foreach ($updates as $v) {
                            RoleAuth::where('role_id', '=', $request->id)->where('auth_id', '=', (int)$v)->update($updates_arr);
                        }
                    }

                },3);
                /**结束事务*/
                return $this->success('分配成功',asset('/role/index'));
            }catch (QueryException $e){
                return $this->error('分配失败');
            }
        }
        $authList = RoleAuth::where('role_id','=',$request->id)->where('status','=','1')->pluck('auth_id');
        return view('admin.role.fp',['authTree'=>Auth::getAuthTree(),'authList'=>$authList,'id'=>$request->id]);
    }
}
